package spring.boot.admin.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import spring.boot.admin.model.SysMenu;
import spring.boot.admin.service.SysMenuService;

import java.util.List;

/**
 * 菜单管理 控制器
 */
@Controller
@RequestMapping("/sys/menu")
public class SysMenuController {

    @Autowired
    private SysMenuService sysMenuService;


    /**
     * 跳转到菜单管理页面
     */
    @GetMapping("to/list")
    @PreAuthorize("hasRole('SYS_MENU_LIST')")
    public String toList() {
        return "sys/menu/list";
    }

    /**
     * 菜单管理  列表查询
     */
    @PostMapping("list")
    @ResponseBody
    @PreAuthorize("hasRole('SYS_MENU_LIST')")
    public List<SysMenu> list(@RequestParam(required = false) Long id) {
        if (id == null) {
            id = 0L;
        }
        return sysMenuService.selectList(id);
    }


    /**
     * 新增菜单
     */
    @PostMapping("insert")
    @ResponseBody
    @PreAuthorize("hasRole('SYS_MENU_ADD')")
    public String insert(@RequestParam(required = false) Long pid,
                         @RequestParam(required = false) String name,
                         @RequestParam(required = false) String url,
                         @RequestParam(required = false) String authority,
                         @RequestParam(required = false) Integer sort,
                         @RequestParam(required = false) Integer enable) {
        if (pid == null || name == null || url == null || authority == null || enable == null || sort == null) {
            return "-1";
        }
        return sysMenuService.insert(pid, name, url, authority, enable, sort);
    }


    /**
     * 删除菜单，删除前要判断是否有角色关联，是否有子菜单
     */
    @PostMapping("deleteById")
    @ResponseBody
    @PreAuthorize("hasRole('SYS_MENU_DELETE')")
    public String deleteById(@RequestParam(required = false) Long id) {
        if (id == null) {
            return "-1";
        }
        return sysMenuService.deleteById(id);
    }


    /**
     * 根据主键id更新数据
     */
    @PostMapping("update")
    @ResponseBody
    @PreAuthorize("hasRole('SYS_MENU_UPDATE')")
    public String update(@RequestParam(required = false) Long id,
                         @RequestParam(required = false) String name,
                         @RequestParam(required = false) String url,
                         @RequestParam(required = false) String authority,
                         @RequestParam(required = false) Integer sort,
                         @RequestParam(required = false) Integer enable) {
        if (id == null || name == null || url == null || authority == null || enable == null) {
            return "-1";
        }
        return sysMenuService.updateMenuById(id, name, url, authority, sort, enable);
    }


}
